<template>
  <div class="change-avatar">
    <CropperAvatar
      ref="cropperRef"
      :show-btn="false"
      :value="img"
      width="120px"
      @change="handlelUpload"
    />
  </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import * as ProfileApi from '@/api/system/profile'
import * as FileApi from '@/api/infra/file'
import { useUserStore } from '@/stores/modules/user'
import { useI18n } from 'vue-i18n'

defineOptions({ name: 'ProfileUserAvatar' })

defineProps({
  img: propTypes.string.def('')
})

const message = useMessage()
const { t } = useI18n()
const userStore = useUserStore()

const cropperRef = ref()
const handlelUpload = async ({ data }) => {
  const res = await FileApi.uploadFile({ file: data, category: 'staff_user_avatar' })
  await ProfileApi.updateUserAvatar(res.path)
  message.success(t('common.updateSuccess'))
  cropperRef.value.close()
  userStore.setUserAvatar(res.path)
}
</script>

<style scoped lang="scss">
.change-avatar {
  img {
    display: block;
    margin-bottom: 15px;
    border-radius: 50%;
  }
}
</style>
